TOP

SQL GROUP BY

SQL GROUP BY 说明

GROUP BY 语句将具有相同值的行分组为汇总行,例如“查找每个国家/地区的客户数量”。

GROUP BY 语句通常与聚合函数(COUNT()、MAX()、MIN()、SUM()、AVG())一起使用,以按一列或多列对结果集进行分组。


GROUP BY 语法

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s)

演示数据库

以下是“Northwind”数据库的“Customers”(“Customers”)表中的示例:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.5021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.5023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

SQL GROUP BY 示例

以下 SQL 语句列出了每个国家/地区的客户数量:

Run SQLSELECT COUNT(CustomerID), Country 
FROM Customers 
GROUP BY Country

以下 SQL 语句列出了每个国家/地区的客户,按从高到低排序:

Run SQLSELECT COUNT(CustomerID), Country 
FROM Customers 
GROUP BY Country 
ORDER BY COUNT(CustomerID) DESC

演示数据库

以下是“Northwind”数据库的“Orders”(“Orders”)表中的示例:

ProductIDOrderIDCustomerIDEmployeeIDOrderDateShipperID
1102489051996-07-043
2102498161996-07-051
3102503441996-07-082
4102518431996-07-081
5102527641996-07-092

以及表“Shippers”(“发件人”)中的示例:

ShipperIDShipperNamePhone
1Speedy Express(503) 555-9831
2United Package(503) 555-3199
3Federal Shipping(503) 555-9931

GROUP BY 与 JOIN 一起使用示例

下面的SQL语句列出了每个发送者发送的订单数量:

Run SQLSELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders 
FROM Orders 
LEFT JOIN Shippers 
ON Orders.ShipperID = Shippers.ShipperID 
GROUP BY ShipperName